package com.ghsc.ghxc.jsb.ui.live.shopping

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.dingpaas.interaction.ImSendMessageToGroupReq
import com.alibaba.dingpaas.interaction.ImSendMessageToGroupRsp
import com.aliyun.aliinteraction.InteractionEngine
import com.aliyun.aliinteraction.base.Callback
import com.aliyun.aliinteraction.base.Error
import com.aliyun.aliinteraction.roompaas.message.model.CusuLiveGoodsModel
import com.blankj.utilcode.util.GsonUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cn.appcore.base.BaseVMFragment
import com.cn.appcore.event.RxBus
import com.cn.appcore.event.RxBusBean
import com.cn.appcore.event.SchedulerTransformer
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setOnFastChildClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.utils.GlideUtil
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.widget.CustomRefreshListener
import com.cn.appcore.widget.RefreshHelper
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.CustSignKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.FragmentLiveCartTabBinding
import com.ghsc.ghxc.jsb.ui.live.view.CustRouter
import com.ghsc.ghxc.jsb.view.NotDataView
import com.scwang.smart.refresh.layout.api.RefreshLayout

/**
 * 类名：LiveCarFragment
 * 创建人 @author： xiaolin
 * 描述 ：Todo...小黄车
 */
class LiveCarFragment : BaseVMFragment<LiveCarViewModel, FragmentLiveCartTabBinding>(R.layout.fragment_live_cart_tab){

    //聊天时id
    private var mGroupId :String =""
    //主播id
    private  var anchorId:String =""

    private var liveId:String =""

    companion object{
        fun newInstance(anchorId :String,mGroupId :String,liveId:String): LiveCarFragment {
            val fragment = LiveCarFragment()
            fragment.mGroupId = mGroupId
            fragment.anchorId=anchorId
            fragment.liveId=liveId
            return fragment
        }
    }

    override fun attachVMClass(): Class<LiveCarViewModel>? {
       return LiveCarViewModel::class.java
    }




    override fun lazyLoad() {

    }


    private val mAdapter: ListAdapter by lazy { ListAdapter() }
    var mList = arrayListOf<CommodityDataBean>()
    private var notDataView: View? = null
    var itemPosition=-1

    var isListing=true

    override fun initView(savedInstanceState: Bundle?) {
        binding.llTop.visibility=View.GONE
        binding.rvList.layoutManager = LinearLayoutManager(requireActivity())
        binding.rvList.adapter = mAdapter
        notDataView = NotDataView.notDataView(requireActivity(), binding.rvList, binding.refreshLayout,"暂无数据")
        mAdapter.setNewInstance(mList)
        mAdapter.addChildClickViewIds(R.id.tvBtnDelete,R.id.tvBtnAdd,R.id.tvBtnExplain)
        mAdapter.setOnFastChildClickListener { view, position ->
            when (view.id) {
                R.id.tvBtnExplain -> {
                    showLoading()
                    itemPosition=position
                    val map: HashMap<String, Any> = HashMap()
                    map["id"] = mAdapter.data[position].id
                    map["is_explain"] = 1
                    loge("商品列表参数：$map")
                    GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onZbCartExplainMethod(it1) }
                }
                R.id.tvBtnAdd -> {
                    showLoading()
                    itemPosition=position
                    isListing=true
                    val map: HashMap<String, Any> = HashMap()
                    map["id"] = mAdapter.data[position].id
                    map["status"] = 1
                    loge("商品列表参数：$map")
                    GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onZbCartStatusMethod(it1) }
                }
                R.id.tvBtnDelete -> {
                    showLoading()
                    itemPosition=position
                    isListing=false
                    val map: HashMap<String, Any> = HashMap()
                    map["id"] = mAdapter.data[position].id
                    map["status"] = 2
                    loge("商品列表参数：$map")
                    GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onZbCartStatusMethod(it1) }
                }
                else -> {}
            }
        }
        initRefreshLayout()
        pageNo=1
        getListData()

        rxBusSubscription = RxBus.getDefault().toObservable(RxBusBean::class.java)
            .compose(SchedulerTransformer())
            .subscribe { rxBusBean ->
                when {
//                    rxBusBean.id == CustSignKey.LIVE_AN_CART && rxBusBean.sign == CustSignKey.LIVE_AN_CART -> {
//                        pageNo=1
//                        getListData()
//                    }
//                    rxBusBean.id == CustKey.ORDER_TAB_LIVE_GOOD_CAR && rxBusBean.sign == CustKey.ORDER_TAB_LIVE_GOOD_CAR -> {
//                        var tabIndex =rxBusBean.anyBean as Int
//                        if(tabIndex==index){
//                            binding.refreshLayout.autoRefresh()
//                        }
//                    }

                }
            }

    }

    private fun initRefreshLayout() {
        RefreshHelper.initRefreshLayout(binding.refreshLayout, object : CustomRefreshListener {
            override fun _onRefresh(refreshLayout: RefreshLayout?) {
                pageNo=1
                getListData()
            }

            override fun _onLoadMore(refreshLayout: RefreshLayout?) {
                pageNo++
                getListData()
            }
        })
    }

    private fun getListData() {
        val map: HashMap<String, Any> = HashMap()
        map["psize"] = 10
        map["pindex"] =pageNo
        map["uid"] = anchorId
        loge("商品列表参数：$map")
        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onZbCartListMethod(it1) }

    }

    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@LiveCarFragment) {
                dismissLoading()
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                showToast(it)
            }
            againLoginMsg.observe(this@LiveCarFragment) {
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                dismissLoading()
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }
            onZbCartStatusData.observe(this@LiveCarFragment){
                dismissLoading()
                showToast("操作成功")
                //推送下架
                if(isListing)
                    CustRouter.sendRefreshMsg("", mGroupId)
                else
                    CustRouter.sendRefreshMsg(mAdapter.getItem(itemPosition).pid, mGroupId)
                pageNo=1
                getListData()
            }
            onZbCartExplainData.observe(this@LiveCarFragment){
                dismissLoading()
                pageNo=1
                getListData()
                //推送讲解

                sendMsg(mAdapter.getItem(itemPosition))



            }
            onZbCartListData.observe(this@LiveCarFragment) {
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                if (pageNo == 1) {
                    if (it.data.list.isNullOrEmpty()){
                        mAdapter.setEmptyView(notDataView!!)
                        mAdapter.replaceData( it.data.list)
                    }else {
                        mAdapter.replaceData( it.data.list)

                    }
                } else {
                    if (!it.data.list.isNullOrEmpty())
                        mAdapter.addData(it.data.list)
                }
//                isInit=true
            }


        }
    }

    //发送消息 推送讲解
    private  fun sendMsg(bean : CommodityDataBean){
        // 1. 向组内全员发消息
        val req = ImSendMessageToGroupReq()
        req.groupId =mGroupId
        // 指定消息类型
        req.type = CustSignKey.LIVE_IM_GOODS
        // 指定是否跳过安全审核
        req.skipAudit = true
        // 指定是否跳过禁言处理
        req.skipMuteCheck = true
        // 指定发送数据
        req.data = GsonUtils.getGson().toJson(bean)
        var interactionService = InteractionEngine.instance().interactionService
        interactionService.sendMessageToGroup(req,object :
            Callback<ImSendMessageToGroupRsp> {
            override fun onSuccess(p0: ImSendMessageToGroupRsp?) {
                loge("发送成功")
                var goodsBean = CusuLiveGoodsModel()
                goodsBean.cart_id=bean.id
                goodsBean. pid=bean.pid
                goodsBean. title=bean.title
                goodsBean. pay_jifen=bean.pay_jifen
                goodsBean. images=bean.images
                goodsBean. is_explain=bean.is_explain
                //直播 主播 发商品
                RxBus.getDefault().post(
                    RxBusBean(
                        CustSignKey.CUST_LIVE_GOODS,
                        CustSignKey.CUST_LIVE_GOODS, goodsBean
                    )
                )
            }
            override fun onError(p0: Error?) {
                loge("发送失败")
            }

        })
    }


    inner class ListAdapter : BaseQuickAdapter<CommodityDataBean, BaseViewHolder>(R.layout.live_cart_list_item) {
        override fun convert(holder: BaseViewHolder, item: CommodityDataBean) {

            GlideUtil.ImageLoad(this.context,item.images,holder.getView(R.id.img))
            holder.setText(R.id.tvTitle,item.title)
                .setText(R.id.tvNum,(holder.layoutPosition+1).toString())
                .setText(R.id.tvPrice,item.pay_jifen)
                .setGone(R.id.tvBtnSub,true)
            //上架==1
            if(item.status==1)
                holder.setGone(R.id.tvBtnAdd,true)
                    .setGone(R.id.tvBtnDelete,false)
            else holder.setGone(R.id.tvBtnAdd,false)
                .setGone(R.id.tvBtnDelete,true)
            //是否讲解
            if(item.is_explain==1)
                holder.setGone(R.id.tvStatus,false)
                    .setGone(R.id.tvBtnExplain,true)
            else holder.setGone(R.id.tvStatus,true)
                .setGone(R.id.tvBtnExplain,false)
        }
    }
}